package com.hongmeng.teamwork.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.hongmeng.teamwork.constants.HttpHeadConstant;
import com.hongmeng.teamwork.entity.base.Result;
import com.hongmeng.teamwork.domain.IUserDomainService;
import com.hongmeng.teamwork.entity.vo.UserVo;
import com.lark.oapi.service.contact.v3.model.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserDomainService userService;

    @GetMapping("/findByDepartment")
    public Result<?> findByDepartment(HttpServletRequest request,
                                        @RequestParam(value = "departmentId", defaultValue = "0", required = false) String departmentId) {
        try {
            List<User> userList = userService.findByDepartment(request.getHeader(HttpHeadConstant.ACCESS_TOKEN), departmentId);
            if (log.isInfoEnabled()) {
                log.info("UserController.findByDepartment.userList: {}", JSON.toJSONString(userList));
            }
            return Result.ok(userList);
        } catch (Exception e) {
            log.error("UserController.findByDepartment.error: {}", e.getMessage(), e);
            return Result.ok("获取部门下用户失败！");
        }
    }

    @GetMapping("/findLoginUserInfo")
    public Result<?> findLoginUser(HttpServletRequest request) {
        try {
            String accessToken = request.getHeader(HttpHeadConstant.ACCESS_TOKEN);
            UserVo userVo = userService.findLoginUser(accessToken);
            if (log.isInfoEnabled()) {
                log.info("UserController.findLoginUserInfo.user: {}", JSON.toJSONString(userVo));
            }
            Preconditions.checkNotNull(userVo, "当前用户暂未登录!");
            return Result.ok(userVo);
        } catch (Exception e) {
            log.error("UserController.findByDepartment.error: {}", e.getMessage(), e);
            return Result.ok(e.getMessage());
        }
    }
}
